Page({
  /**
   * 页面的初始数据
   */
  data: {
    messages: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    try {
      var value = wx.getStorageSync('shoucang')
      var that = this;
      if (value) {
        // 为每个项添加 isTouchMove 字段
        value = value.map(item => ({ ...item, isTouchMove: false }));
        that.setData({
          messages: value
        })
      }
    } catch (e) {
      // Do something when catch error
      console.error('Failed to load data:', e);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 右滑删除
   */
  touchstart(e) {
    const index = e.currentTarget.dataset.index;
    const startX = e.changedTouches[0].clientX;
    const messages = this.data.messages.map((message, i) => ({
      ...message,
      isTouchMove: i === index
    }));
    this.setData({ startX, messages });
  },

  touchmove(e) {
    const index = e.currentTarget.dataset.index;
    const startX = this.data.startX;
    const touchMoveX = e.changedTouches[0].clientX;
    const messages = this.data.messages.map((message, i) => ({
      ...message,
      isTouchMove: i === index && startX - touchMoveX > 50
    }));
    this.setData({ messages });
  },

  removeMessage(e) {
    const id = e.currentTarget.dataset.id;
    const messages = this.data.messages.filter(message => message.id !== id);
    this.setData({ messages });
    wx.setStorageSync('shoucang', messages);
    wx.showToast({
      title: '删除成功',
      icon: 'success',
      duration: 2000
    });
  },

  removeSelectedMessages() {
    const messages = this.data.messages.filter(message => !message.isTouchMove);
    this.setData({ messages });
    wx.setStorageSync('shoucang', messages);
    wx.showToast({
      title: '删除成功',
      icon: 'success',
      duration: 2000
    });
  }

});
